package com.changgou.system.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取客户端的访问ip
 */
@Component
public class IpFilter implements GlobalFilter, Ordered {
    /**
     * 具体逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //客户端访问ip
        System.out.println("经过第一个过滤器:IpFilter");
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String hostName = remoteAddress.getHostName();
        System.out.println("hostName:" +hostName);
        System.out.println("remoteAddress:" + remoteAddress.getHostName());
        if (blackIp(hostName)){
            //是黑客,设置响应状态码为未授权
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器的执行优先级,返回值越小,执行优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }

    //判断是否是黑客ip
    boolean blackIp(String hostName) {
        List<String> ip = new ArrayList<>();
        ip.add("22.22.22.22");
        for (String s : ip) {
            if (hostName.equals(s)){
                //是黑客
                return true;
            }
        }

        return false;
    }
}
